<template>
  <!-- 只读状态显示 -->
  <span v-if="readonly" :style="readonlyStyle">
    {{ displayValue || '--' }}
  </span>

  <!-- 可编辑状态显示 -->
  <div v-else class="select-container">
    <el-select 
      v-model="selectedCommodityId" 
      :disabled="disabled" 
      filterable 
      remote 
      clearable 
      reserve-keyword
      :remote-method="remoteSearch" 
      :loading="loading" 
      :placeholder="placeholder || `请选择${label}`"
      @change="handleChange"
      :style="{ width: width }">
      
      <!-- 商品选项 暂时用于贵金属，先只显示规格名称，规格名称对应了贵金属自身名称 -->
      <el-option 
        v-for="commodity in options" 
        :key="commodity.id" 
        :label="commodity.standard" 
        :value="commodity.id">
        <span>{{ commodity.standard }}</span>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { DataPage } from '../../network/communicationConverter'
import { Definition } from '../../engine/common/definition'
import { CommodityUiAction } from '../../engine/uiAction/commodityUiAction'
import { SubCommodityFilter } from '../../engine/commodity/subCommodity'

export default {
  name: 'SubcommoditySelect',
  props: {
    modelValue: {
      type: Object,
      default: null
    },
    placeholder: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    label: {
      type: String,
      default: '商品'
    },
    width: {
      type: String,
      default: '100%'
    },
    readonlyWidth: {
      type: String,
      default: null
    },
    commodityUiActionProps: {
      type: Object,
      default: null
    },
    filterProps: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'change'],
  data() {
    return {
      selectedCommodityId: null,
      options: [],
      loading: false,
      lastQuery: '',
      filter: this.filterProps || new SubCommodityFilter(),
      commodityUiAction: this.commodityUiActionProps || new CommodityUiAction()
    }
  },
  computed: {
    displayValue() {
      return this.modelValue ? `${this.modelValue.standard}` : ''
    },
    readonlyStyle() {
      if (this.readonlyWidth) {
        return { width: this.readonlyWidth, display: 'inline-block' };
      }
      return {};
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        if (val) {
          this.selectedCommodityId = val.id;
        } else {
          this.selectedCommodityId = null;
        }
      }
    }
  },
  methods: {
    async remoteSearch(query) {
      if (query === this.lastQuery) return
      
      this.lastQuery = query
      this.loading = true
      
      try {
        const res = await this.commodityUiAction.getCommoditySpecList(
          new DataPage(1, 0, Definition.gDefualPullDownPageSize),
          this.filter.toJson()
        )
        
        if (res.data && res.data.dataList.length > 0) {
          this.options = res.data.dataList
        } else {
          this.options = []
        }
      } catch (error) {
        console.error('subcommodityselect 搜索商品失败:', error)
      } finally {
        this.loading = false
      }
    },
    handleChange(val) {
      const selectedCommodity = this.options.find(u => u.id === val)
      if (selectedCommodity) {
        this.$emit('update:modelValue', selectedCommodity)
        this.$emit('change', selectedCommodity)
      } else {
        this.$emit('update:modelValue', null)
        this.$emit('change', null)
      }
    },
    async loadDefaultOptions() {
      this.loading = true
      try {                
        const res = await this.commodityUiAction.getCommoditySpecList(
          new DataPage(1, 0, Definition.gDefualPageSize),
          this.filter.toJson()
        )
        
        if (res.data && res.data.dataList.length > 0) {
          this.options = res.data.dataList
        }
      } catch (error) {
        console.error('加载商品失败:', error)
      } finally {
        this.loading = false
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.loadDefaultOptions()
    })
  }
}
</script>

<style scoped>
.select-container {
  display: block;
  width: 100%;
  text-align: left;
}

.select-container :deep(.el-select) {
  width: 100%;
}
</style>